<?php

/*-----------------------------------------------------------------------------------

	General Frontend theme features

-----------------------------------------------------------------------------------*/
global $prefix;



/*-----------------------------------------------------------------------------------*/
/*	Ajax Loader (Isotope)
/*-----------------------------------------------------------------------------------*/
if( !function_exists( 'sr_load_more_callback' ) ) {
	function sr_load_more_callback() {
		global $wpdb;
		global $prefix;
		
		$page = intval( $_POST['page'] );
		$type =  $_POST['type'];
		
		if ($type == 'post') {
			query_posts( array(
				'post_type' => array('post'),
				'paged' => $page
				) 
			);
			get_template_part( 'includes/loop', 'blog');
		} 
		else if ($type == 'portfolio') {
			$sr_portfoliocount = get_option($prefix.'_portfoliocount');
			query_posts( array(
				'posts_per_page'=> $sr_portfoliocount,
				'paged' => $page,
				'portfolio_category' => get_query_var('portfolio_category'),
				'm' => get_query_var('m'),		   
				'w' => get_query_var('w'),
				'post_type' => array('portfolio')
				) 
			);
			get_template_part( 'includes/loop', 'portfolio');
		}
		
		die(); // this is required to return a proper result
	}
}
add_action('wp_ajax_nopriv_sr_load_more', 'sr_load_more_callback'); 
add_action('wp_ajax_sr_load_more', 'sr_load_more_callback');



/*-----------------------------------------------------------------------------------*/
/*	Load more button (isotope)
/*-----------------------------------------------------------------------------------*/
if( !function_exists( 'loadmore' ) ) {
	function loadmore($type, $max_num_page) {
		if (!$type) { $type = 'post'; }
		if ($max_num_page > 1) { 
			echo '<div id="load-more"><a href="#" data-maxnumpage="'.$max_num_page.'" data-type="'.$type.'">'.__('Load More', 'sr_mila_theme').'</a></div>';
		}
	}
}




/*-----------------------------------------------------------------------------------*/
/*	Ajax Loader (Content)
/*-----------------------------------------------------------------------------------*/
if( !function_exists( 'sr_get_content_callback' ) ) {
	function sr_get_content_callback() {
		global $wpdb;
		global $prefix;
		
		$id =  $_POST['id'];
		$type =  $_POST['type'];
		
		if ($type == 'post') {
			// Count the views
			if(!isset($_COOKIE["viewscookie".$id]) && !isset($_POST['countlikes'])) { 
				sr_setPostMeta($id, 'views');
				setcookie("viewscookie".$id, 'yes', time()+3600, '/');
			}
			query_posts( 'p='.$id );
			get_template_part( 'includes/singlepost', 'blog');
		} 
		else if ($type == 'portfolio') {
			query_posts( 'p='.$id.'&post_type=portfolio' );
			get_template_part( 'includes/singlepost', 'portfolio');
		}
		
		die(); // this is required to return a proper result
	}
}
add_action('wp_ajax_nopriv_sr_get_content', 'sr_get_content_callback'); 
add_action('wp_ajax_sr_get_content', 'sr_get_content_callback');




/*-----------------------------------------------------------------------------------*/
/*	Ajax Loader (Likes)
/*-----------------------------------------------------------------------------------*/
if( !function_exists( 'sr_like_callback' ) ) {
	function sr_like_callback() {
		global $wpdb;
		
		$id = intval( $_POST['id'] );
		
		// Count the likes
		if (!isset($_COOKIE["likescookie".$id])) { 
			sr_setPostMeta($id, 'likes'); 
			setcookie("likescookie".$id, 'yes', time()+100000, '/'); 
			echo sr_getPostMeta($id, 'likes');
		} else {
			echo 'cookieset';	
		}
		
		die(); // this is required to return a proper result
	}
}
add_action('wp_ajax_nopriv_sr_like', 'sr_like_callback'); 
add_action('wp_ajax_sr_like', 'sr_like_callback');



/*-----------------------------------------------------------------------------------*/
/*	Side feature
/*-----------------------------------------------------------------------------------*/
function sr_sideFeature($features) {
	global $prefix;
	
	$features = explode('|||', $features);
	$i = 0;
	foreach ($features as $f) {
		if ($i == 0) {
		
		$item = explode('|', $f);
		$options = explode('~~', $item[1]);
		
		switch ( $item[0] ) {
			
			// ------------------------ Map
			case "googlemap":
					$title = $options[0];
					$latlong = $options[1];
					$mapinfo = $options[2];
					
					?>
                    <div class="mainside-bg"></div>
                    	<div id="map"></div>
						<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
                        <script type="text/javascript">
                          function mapinitialize() {
                            // FIND YOUR LATITUDE & LONGITUDE  -> http://itouchmap.com/latlong.html  
                            var myLatlng = new google.maps.LatLng(<?php echo $latlong; ?>);
                            var myOptions = {
                              zoom: 14,
                              center: myLatlng,
                              mapTypeId: google.maps.MapTypeId.ROADMAP
                            }
                            var map = new google.maps.Map(document.getElementById("map"), myOptions);
                            
                            var marker = new google.maps.Marker({
                                position: myLatlng, 
                                map: map
                            });
                            
                            <?php if ( $mapinfo !== '' || count($mapinfo) > 1 ) { 
                            $mapinfo = str_replace(chr(13),'<br>',$mapinfo);
                            $mapinfo = str_replace(chr(10),'',$mapinfo);
                            ?>
                            var infowindow = new google.maps.InfoWindow();
                              infowindow.setContent('<?php echo $mapinfo; ?>');
                              infowindow.open(map, marker);
                            <?php } ?>
                            
                          }
                          mapinitialize();
                        </script>
                    <?php
				break;
				
			// ------------------------ Background
			case "background":
				$title = $options[0];
				$image = $options[1];
				?>
                <div id="fullscreen-bg">
                    <img src="<?php echo $image; ?>" />
                </div>
                <?php
				break;
				
			// ------------------------ Custom
				case "custom":
					$custom = $options[1];
					?>
                    <div id="side" class="mainside">
            			<div id="side-section" class="clearfix">
                        	<div class="entry">
							<?php echo $custom; ?>
                            </div>
                        </div>
                    </div> <!-- END #side --> 
                    <div class="mainside-bg"></div>
                    <?php
				break;
		}
		}
		$i++;
	}
	
}


/*-----------------------------------------------------------------------------------*/
/*	Pagination on single item view
/*-----------------------------------------------------------------------------------*/
if( !function_exists( 'sr_singlepagination' ) ) {
	function sr_singlepagination($type,$start,$end) {
		global $prefix;
		
		$prev_item = get_adjacent_post(false,'',false) ; 
		$prev_post = get_post($prev_item->ID);
		$next_item = get_adjacent_post(false,'',true) ;
		$next_post = get_post($next_item->ID);
		
		if (is_single() && get_post_type() == 'portfolio' ) { $closelink = get_permalink( get_option($prefix.'_portfoliopage') ); }
		else if (is_single() && get_post_type() == 'post' ) { $closelink = get_permalink( get_option('page_for_posts') ); }
		
		if ($prev_item->ID || $next_item->ID) {
			if ($start) { echo $start; }
			echo '<ul>';
			if ($prev_item->ID) { echo '<li><a class="prev loadcontent" data-id="'.$prev_item->ID.'" data-slug="'.$prev_item->post_name.'" data-type="'.get_post_type().'" href="'.get_permalink( $prev_item->ID ).'" title="'.$prev_post->post_title.'">'.__('&lsaquo; Previous', 'sr_mila_theme').'</a></li>'; }
			echo '<li><a class="close closecontent" href="'.$closelink.'" title="Close">'.__('Close', 'sr_mila_theme').'</a></li>';
			if ($next_item->ID) { echo '<li><a class="next loadcontent" data-id="'.$next_item->ID.'" data-slug="'.$next_item->post_name.'" data-type="'.get_post_type().'" href="'.get_permalink( $next_item->ID ).'" title="'.$next_post->post_title.'">'.__('Next &rsaquo;', 'sr_mila_theme').'</a></li>'; }
			echo '</ul>';
			if ($start) { echo $end; }
		}
		
	}						
}
	
	
	
/*-----------------------------------------------------------------------------------*/
/*	Share Button
/*-----------------------------------------------------------------------------------*/
if( !function_exists( 'sr_sharebutton' ) ) {
	function sr_sharebutton() {
		global $wp_query;	
			
		$postid = $wp_query->post->ID;
		$og_title = get_the_title( $postid );
		$og_desc = get_post($postid);
		$og_desc = explode(' ', $og_desc->post_content, 15);
		$og_desc = preg_replace('/<img[^>]+./','', $og_desc);
		$og_desc = preg_replace( '/<blockquote>.*<\/blockquote>/', '', $og_desc );
		array_pop($og_desc);
		$og_desc = implode(" ",$og_desc).'...';
		$og_desc = strip_tags($og_desc);
		$og_url = get_permalink( $postid );
		$og_img = wp_get_attachment_image_src( get_post_thumbnail_id( $postid ), 'medium' );;
		$og_img = $og_img[0];
		
		?>
		<ul class="sharelinks clearfix">
			<li><a href="" onclick="window.open('http://www.facebook.com/sharer/sharer.php?s=100&amp;p[title]=<?php echo $og_title ?>&amp;p[url]=<?php the_permalink(); ?>&amp;p[summary]=<?php echo urlencode($og_desc); ?>&amp;p[images][0]=<?php echo $og_img; ?>','','width=900, height=500, toolbar=no, status=no'); return(false);" title="Facebook Share"><img src="<?php echo get_template_directory_uri(); ?>/files/images/facebook-share.png" alt="facebook share" /></a></li>
			<li><a href="" onclick="window.open('https://twitter.com/intent/tweet?text=Tweet%20this&amp;url=<?php the_permalink(); ?>','','width=650, height=350, toolbar=no, status=no'); return(false);" title="Twitter Share"><img src="<?php echo get_template_directory_uri(); ?>/files/images/tweet-share.png" alt="twitter share" /></a></li>
			<li><a href="" onclick="window.open('https://plusone.google.com/_/+1/confirm?hl=en-US&amp;url=<?php the_permalink(); ?>&amp;image<?php echo $og_img; ?>','','width=900, height=500, toolbar=no, status=no'); return(false);" title="Google Plus Share"><img src="<?php echo get_template_directory_uri(); ?>/files/images/google-share.png" alt="google share" /></a></li>
			<li><a href="" onclick="window.open('http://pinterest.com/pin/create/bookmarklet/?media=<?php echo $og_img; ?>&amp;url=<?php the_permalink(); ?>','','width=650, height=350, toolbar=no, status=no'); return(false);" title="Pin it"><img src="<?php echo get_template_directory_uri(); ?>/files/images/pinterest-share.png" alt="pinterest share" /></a></li>
		</ul>
		
		<?php
	}
}
	

/*-----------------------------------------------------------------------------------*/
/*	Custom Filter Output (Isotope Filter)
/*-----------------------------------------------------------------------------------*/
class sr_filter_output extends Walker_Nav_Menu
{
      function start_el(&$output, $item, $depth, $args)
      {
           global $wp_query;
           $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

           $output .= $indent . '<li>';
			
			if ($item->attr_title == 'all') {
				
				$attributes = ' class="active" data-option-value="*"';
				
			} else {
			
				$title = $item->title;
				if ($item->attr_title !== '') { $title = $item->attr_title; }
				$title = strtolower($title);
				$replace = array(" ", "'", '"', "&amp;",  "amp;", "&");
				$title = str_replace($replace, "", $title);
				$attributes = ' data-option-value=".'.$title.'"';
				$attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
				$attributes .= ! empty( $item->title )        ? ' title="'   . esc_attr( $item->title        ) .'"' : '';

			}

            $item_output = $args->before;
            $item_output .= '<a'. $attributes .'>';
            $item_output .= $args->link_before .apply_filters( 'the_title', $item->title, $item->ID );
            $item_output .= '</a>';
            $item_output .= $args->after;

            $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
            }
	  
}


	


/*-----------------------------------------------------------------------------------*/
/*	Count/Get/Delete Views/Likes  
/*-----------------------------------------------------------------------------------*/
function sr_getPostMeta($postID, $method) {
	global $prefix;
    $count_key = $prefix.'_post_'.$method;
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        return "0";
    }
    return $count;
}


function sr_setPostMeta($postID, $method) {
	global $prefix;
    $count_key = $prefix.'_post_'.$method;
	
	## ALL TIME COUNTS
	$alltime = get_post_meta($postID, $count_key, true);
    if($alltime==''){
        $alltime = 1;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, $alltime);
    }else{
        $alltime++;
        update_post_meta($postID, $count_key, $alltime);
    }
	##
	
}

function sr_resetPostMeta($method) {
    global $prefix;
	$count_key = $prefix.'_post_'.$method;
	
	$posts = get_posts('numberposts=-1&type=post');
	foreach ( $posts as $p ) { 
		delete_post_meta($p->ID, $count_key);
	}
	
}


?>